package com.jeesite.modules.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LoginFilter implements Filter {

    CatchService catchService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //过滤器注入service，原因：过滤器执行的时候，service还没有被实例化注入
        ServletContext sc = filterConfig.getServletContext();
        WebApplicationContext cxt =  WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null) {
            if (catchService == null) {
                catchService = cxt.getBean(CatchService.class);
            }
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getHeader("token");
        // 获取用户的认证信息（这里示例仅从会话中获取）
        String user_id = null;
        Object user = null;
        if(token != null){
            user = catchService.getHashCache("USERTOKEN", token);
        }

        // 检查用户是否已登录
        if (user == null ) {


            // 用户未登录，重定向到登录页面
            // 设置响应头
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("请先登录");

            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(user.toString());
        String id = jsonObject.getString("id");
        servletRequest.setAttribute("user_id",jsonObject.get("id"));
        if(StringUtils.isEmpty(id)){
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("请先登录");
            return;
        }
        String mobile = jsonObject.getString("mobile");
        if(StringUtils.isEmpty(mobile)){
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("此账号未绑定手机号，请先绑定手机号");
            return;
        }


        // 用户已登录，继续处理请求
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        // 销毁代码（如果有的话）
    }



    public static void main(String[] args) {
        Map<String,String> map= new HashMap<>();
        map.put("name","lisi");
        Object o = JSONObject.toJSON(map);
        JSONObject o1 = (JSONObject) o;
        System.out.println(o1.toJSONString());
    }
}